package com.desksoft.ecommerce.util.remote;

import org.springframework.remoting.caucho.HessianProxyFactoryBean;
import org.springframework.remoting.support.UrlBasedRemoteAccessor;

import com.desksoft.ecommerce.util.holder.ApplicationContextHolder;
import com.desksoft.utility.remote.RemoteFactory;

public class DynamicRemoteInterface {

	/**
	 * 获取服务层远程接口代理
	 * @param serviceUrl			远程服务接口的ServiceUrl
	 * @param interfaceClass		远程服务接口的完整包路径
	 * @return
	 */
	public Object getInterface(String serviceUrl, Class<?> interfaceClass){

		Object result = null;
		UrlBasedRemoteAccessor remoteAccessor = getAccessor(serviceUrl, interfaceClass);
		/**
		 * 暂时没找到其他办法，先用这种暴力方式获取。
		 * 找到了再改
		 */
		if (remoteAccessor instanceof HessianProxyFactoryBean){
			result = ((HessianProxyFactoryBean) remoteAccessor).getObject();
		}
		
		return result;
	}
	
	protected UrlBasedRemoteAccessor getAccessor(String serviceUrl, Class<?> interfaceClass){
		
		RemoteFactory remoteFactory = (RemoteFactory) ApplicationContextHolder.getBean("remoteFactory");
		UrlBasedRemoteAccessor remoteAccessor = remoteFactory.getAccessor();
		remoteAccessor.setServiceUrl(serviceUrl);
		remoteAccessor.setServiceInterface(interfaceClass);
		remoteAccessor.afterPropertiesSet();
		
		return remoteAccessor;
	}
	
}
